package org.chuan.hisports.util;


import org.apache.commons.io.FilenameUtils;
import org.chuan.hisports.service.Imp.UserServiceImp;
import org.chuan.hisports.service.UserService;
import org.omg.CORBA.Request;
import org.springframework.http.HttpRequest;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

//用来处理图像上传，重命名，存储等功能
public class ImageUtil {

    public String upload(String uid, MultipartFile pictureFile,String path) throws IOException {
        //获取文件的拓展名
        String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
        //重命名新的拓展名
        String filename = uid+"."+ext;
        //获取要保存文件的文件夹

        System.out.println(path+"\\"+filename);
        File newfile = new File(path,filename);
        if (!newfile.exists())
            newfile.mkdirs();
        //文件转存
        pictureFile.transferTo(newfile);
        //文件路径上传至数据库
        String datapath = "/vacatar/"+filename;
        System.out.println(datapath);
        return datapath;

    }

    //base64解密，并存入文件夹

    public String phone(String uid,String imgdata,String path){
        String bs = "data:image/png;base64,";
        String base = imgdata.replace(bs, "");
        BASE64Decoder decoder = new BASE64Decoder();
        String imgFilePath = null;
        String filename = null;

        try {
            //解码
            byte[] b = decoder.decodeBuffer(base);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            filename = uid+".png";
            imgFilePath = path+"\\"+filename;
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();

        } catch (Exception e) {
            return "error";
        }


        return filename;
    }
}
